﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using fanfu.Common;
using fanfu.Business;
using fanfu.Model;

public partial class Leaveword : BasePage
{
    //所有留言信息
    private DataTable __Leaveword = new DataTable();
    //留言信息预览
    public string strLeavewordMsg = string.Empty;

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string leaveName = this.searchLeaveName.Value.Trim();
        string leaveCaption = this.searchLeaveCaption.Value.Trim();
        string leaveContent = this.searchLeaveContent.Value.Trim();
        string startTime = this.searchStartCreateTime.Value.Trim();
        string endTime = this.searchEndCreateTime.Value.Trim();
        byte answerFlag = byte.Parse(this.searchAnswerFlag.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM Leaveword WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (leaveName != "")
        {
            sqlString += "AND LeaveName like @LeaveName ";
            paraList.Add(new SqlParameter("@LeaveName", "%" + leaveName + "%"));
        }
        if (leaveCaption != "")
        {
            sqlString += "AND LeaveCaption like @LeaveCaption ";
            paraList.Add(new SqlParameter("@LeaveCaption", "%" + leaveCaption + "%"));
        }
        if (leaveContent != "")
        {
            sqlString += "AND LeaveContent like @LeaveContent ";
            paraList.Add(new SqlParameter("@LeaveContent", "%" + leaveContent + "%"));
        }
        if (startTime != "")
        {
            sqlString += "AND LeaveTime>=@StartCreateTime ";
            paraList.Add(new SqlParameter("@StartCreateTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND LeaveTime<@EndCreateTime ";
            paraList.Add(new SqlParameter("@EndCreateTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (answerFlag != 0)
        {
            sqlString += "AND AnswerFlag=@AnswerFlag ";
            paraList.Add(new SqlParameter("@AnswerFlag", answerFlag));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        sqlString += "ORDER BY LeaveTime ASC";
        #endregion

        //给数据列表赋值
        __Leaveword = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Leaveword.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Leaveword.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchLeaveName.Value = "";
        this.searchLeaveCaption.Value = "";
        this.searchLeaveContent.Value = "";
        this.searchStartCreateTime.Value = "";
        this.searchEndCreateTime.Value = "";
        this.searchAnswerFlag.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __Leaveword = new LeavewordRule().GetAllLeavewordInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Leaveword.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Leaveword.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.deleteID.Value = "";          //清除删除的ID
        this.lockIP.Value = "";            //清除封杀的IP
        RunJavascript("ResetInput();", true);  //JS清空控件值
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定回复状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchAnswerFlag, typeof(LeavewordAnswerFlag));
            //绑定留言状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(LeavewordFlag));
            EnumPlus.BindDesEnumToListControl(this.drpFlag, typeof(LeavewordFlag));
            this.drpFlag.Items.RemoveAt(0);

            //判断请求是否来自查看新消息
            if (string.IsNullOrEmpty(Request.QueryString["news"]))
            {
                this.searchFlag.SelectedIndex = 0;
                BindAllData(this.rptDataList, 1);
            }
            else if (Request.QueryString["news"] == "noVerify")
            {
                this.searchFlag.Items.FindByValue(((byte)LeavewordFlag.noVerify).ToString()).Selected = true;
                BindDataBySearch(this.rptDataList, 1);
            }
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 通过审核
    protected void lbtnPass_Click(object sender, EventArgs e)
    {
        string sqlString = string.Format("UPDATE Leaveword SET Flag={0} WHERE ID={1}", (int)LeavewordFlag.passVerify, this.editID.Value);
        int result = SqlHelper.ExecuteCommand(sqlString);
        if (result == 1)
            RunJavascript("PopupMsg('success','恭喜您,留言审核通过！');", true);
        else
            RunJavascript("PopupMsg('error','错误,留言审核失败！');", true);
        
        //刷新页面,更新消息数
        Response.Redirect("Leaveword.aspx");
    }
    #endregion

    #region 回复事件
    protected void lbtnReply_Click(object sender, EventArgs e)
    {
        //选项卡跳转
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            LeavewordModel leaveword = new LeavewordRule().GetLeavewordByID(editID);

            //显示留言信息到页面
            strLeavewordMsg += "<li><strong>留言ID：</strong>" + leaveword.ID + "</li>";
            strLeavewordMsg += "<li><strong>留言者：</strong>" + leaveword.LeaveName + "</li>";
            strLeavewordMsg += "<li><strong>留言邮箱：</strong>" + leaveword.LeaveEmail + "</li>";
            strLeavewordMsg += "<li><strong>留言网址：</strong>" + leaveword.LeaveUrl + "</li>";
            strLeavewordMsg += "<li><strong>留言标题：</strong>" + leaveword.LeaveCaption + "</li>";
            strLeavewordMsg += "<li><strong>留言内容：</strong>" + leaveword.LeaveContent + "</li>";
            strLeavewordMsg += "<li><strong>留言IP：</strong>" + leaveword.LeaveIP + "</li>";
            strLeavewordMsg += "<li><strong>留言时间：</strong>" + leaveword.LeaveTime.ToString() + "</li>";

            //绑定值到页面控件
            this.txtAnswerName.Value = leaveword.AnswerName;
            this.txtAnswerContent.Value = leaveword.AnswerContent;
            this.chkAnswerFlag.Checked = leaveword.AnswerFlag == (byte)LeavewordAnswerFlag.yesAnswer ? true : false;
            this.drpFlag.ClearSelection();
            this.drpFlag.Items.FindByValue(leaveword.Flag.ToString()).Selected = true;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new LeavewordRule().DeleteLeaveword(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //刷新页面,更新消息数
        Response.Redirect("Leaveword.aspx");
    }
    #endregion

    #region 封杀IP
    protected void lbtnLockIP_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(this.lockIP.Value.Trim()))
        {
            int result = new BrowseLimitRule().InsertBrowseLimit(this.lockIP.Value.Trim());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,封杀IP成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,封杀IP失败！');", true);
            }

            //清理控件状态
            ClearInputState();
        }
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string answerName = this.txtAnswerName.Value.Trim();
        if (string.IsNullOrEmpty(answerName))
            answerName = CookieHelper.GetCookie("userAlias");
        string answerContent = this.txtAnswerContent.Value.Trim();
        byte answerFlag = this.chkAnswerFlag.Checked == true ? (byte)LeavewordAnswerFlag.yesAnswer : (byte)LeavewordAnswerFlag.noAnswer;
        byte flag = byte.Parse(this.drpFlag.SelectedItem.Value);
        DateTime answerTime = DateTime.Now;
        string editID = this.editID.Value;

        //更新回复
        string sqlString = "UPDATE Leaveword SET AnswerName=@AnswerName, AnswerContent=@AnswerContent, AnswerTime=@AnswerTime, AnswerFlag=@AnswerFlag, Flag=@Flag WHERE ID=@ID";
        List<SqlParameter> paraList = new List<SqlParameter>();
        paraList.Add(new SqlParameter("@AnswerName", answerName));
        paraList.Add(new SqlParameter("@AnswerContent", answerContent));
        paraList.Add(new SqlParameter("@AnswerTime", answerTime));
        paraList.Add(new SqlParameter("@AnswerFlag", answerFlag));
        paraList.Add(new SqlParameter("@Flag", flag));
        paraList.Add(new SqlParameter("@ID", editID));
        int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
        if (result == 1)
        {
            RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
        }
        else
        {
            RunJavascript("PopupMsg('error','错误,更新失败！');", true);
            RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
        }
        
        //刷新页面,更新消息数
        Response.Redirect("Leaveword.aspx");
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}